<template>
  <div>
    <!-- 可拖动的小助手图标 -->
    <div
      class="assistant-icon"
      :style="{ left: position.x + 'px', top: position.y + 'px' }"
      @mousedown="startDrag"
      @mouseup="handleMouseUp"
    >
      <el-icon :size="30"><Service /></el-icon>
    </div>

    <!-- 聊天框 -->
    <el-dialog
      v-model="showChat"
      title="智能助手"
      :modal="false"
      custom-class="chat-dialog"
      :close-on-click-modal="false"
      width="800px"
      :style="{ left: chatPosition.x + 'px', top: chatPosition.y + 'px' }"
    >
      <!-- 添加自定义header用于拖动 -->
      <template #header>
        <div
          class="dialog-header-custom"
          @mousedown="startChatDrag"
        >
          智能助手
        </div>
      </template>

      <div class="chat-container">
        <div class="chat-messages">
          <!-- 添加消息显示 -->
          <div v-for="(msg, index) in messages" :key="index"
               :class="['message', msg.type === 'user' ? 'user-message' : 'assistant-message']">
            <div class="message-content">{{ msg.content }}</div>
          </div>
        </div>

        <div class="chat-input">
          <el-input
            v-model="message"
            placeholder="请输入消息..."
            @keyup.enter="sendMessage"
          >
            <template #append>
              <el-button @click="sendMessage" :loading="loading" :disabled="loading" type="primary">发送</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { Service } from '@element-plus/icons-vue'
import { sendMessageToBackend, fetchChatHistory } from '@/api/chatApi'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/index.js' // 假设你有一个 userStore

const showChat = ref(false)
const message = ref('')
// 添加消息数组
const messages = ref([
  { type: 'assistant', content: '你好！我是你的智能助手，有什么可以帮你的吗？' }
])

const position = reactive({
  x: window.innerWidth - 100,
  y: window.innerHeight - 100
})

let isDragging = false
let startX = 0
let startY = 0
let dragStartTime = 0
let hasMoved = false

const userStore = useUserStore()

const startDrag = (e: MouseEvent) => {
  isDragging = true
  hasMoved = false
  dragStartTime = Date.now()
  startX = e.clientX - position.x
  startY = e.clientY - position.y

  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}

const onDrag = (e: MouseEvent) => {
  if (isDragging) {
    hasMoved = true
    position.x = e.clientX - startX
    position.y = e.clientY - startY
  }
}

const stopDrag = () => {
  isDragging = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

const handleMouseUp = (e: MouseEvent) => {
  const dragEndTime = Date.now()
  const dragDuration = dragEndTime - dragStartTime

  // 如果拖动时间小于200ms且没有移动，则认为是点击
  if (dragDuration < 200 && !hasMoved) {
    toggleChat()
  }
}

const toggleChat = async () => {
  showChat.value = !showChat.value
  if (showChat.value) {
    try {
      // const history = await fetchChatHistory(userStore.user.uid) // 传递用户uid
    } catch (error) {
      console.error(error)
      ElMessage({
        type: 'error',
        message: '获取聊天记录时出错，请稍后重试。'
      })
    }

    // 使用 Vue 的 nextTick 确保对话框已经渲染完成
    nextTick(() => {
      const dialog = document.querySelector('.el-dialog') as HTMLElement
      if (dialog) {
        const windowWidth = window.innerWidth
        const windowHeight = window.innerHeight
        const dialogWidth = dialog.offsetWidth
        const dialogHeight = dialog.offsetHeight

        // 更新聊天框位置，使其水平和垂直居中
        chatPosition.x = (windowWidth - dialogWidth) / 2
        chatPosition.y = (windowHeight - dialogHeight) / 2 - 150
      }
    })
  }
}

const loading = ref(false) // 添加加载状态

const sendMessage = async () => {
  if (message.value.trim()) {
    messages.value.push({
      type: 'user',
      content: message.value
    })

    loading.value = true
    try {
      const data = message.value;
      message.value = ''
      setTimeout(() => {
        const messagesContainer = document.querySelector('.chat-messages')
        if (messagesContainer) {
          messagesContainer.scrollTop = messagesContainer.scrollHeight
        }
      }, 100)
      const reply = await sendMessageToBackend(data) // 传递用户uid
      messages.value.push({
        type: 'assistant',
        content: reply
      })
    } catch (error) {
      messages.value.push({
        type: 'assistant',
        content: '抱歉，发送消息时出错。'
      })
    } finally {
      loading.value = false
    }

    // 滚动到底部
    setTimeout(() => {
      const messagesContainer = document.querySelector('.chat-messages')
      if (messagesContainer) {
        messagesContainer.scrollTop = messagesContainer.scrollHeight
      }
    }, 100)
  }
}

// 添加聊天框位置状态
const chatPosition = reactive({
  x: 0,
  y: 0
})

// 聊天框拖动相关变量
let isChatDragging = false
let chatStartX = 0
let chatStartY = 0

// 聊天框拖动相关函数
const startChatDrag = (e: MouseEvent) => {
  isChatDragging = true
  chatStartX = e.clientX - chatPosition.x
  chatStartY = e.clientY - chatPosition.y

  document.addEventListener('mousemove', onChatDrag)
  document.addEventListener('mouseup', stopChatDrag)
}

const onChatDrag = (e: MouseEvent) => {
  if (isChatDragging) {
    chatPosition.x = e.clientX - chatStartX
    chatPosition.y = e.clientY - chatStartY
  }
}

const stopChatDrag = () => {
  isChatDragging = false
  document.removeEventListener('mousemove', onChatDrag)
  document.removeEventListener('mouseup', stopChatDrag)
}
</script>

<style scoped>
.assistant-icon {
  position: fixed;
  z-index: 2000;
  width: 50px;
  height: 50px;
  background-color: #0085d0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
  user-select: none; /* 防止拖动时选中文本 */
}

.assistant-icon:hover {
  transform: scale(1.1);
}

.chat-dialog {
  position: fixed !important;
  margin: 0 !important;
}

.chat-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
  margin-bottom: 10px;
  border-radius: 4px;
}

.message {
  margin-bottom: 10px;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.assistant-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 4px;
  word-break: break-word;
}

.user-message .message-content {
  background-color: #0085d0;
  color: white;
}

.assistant-message .message-content {
  background-color: white;
  border: 1px solid #e4e7ed;
}

.chat-input {
  padding: 10px 0;
}

:deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
}

:deep(.el-dialog__headerbtn) {
  top: 20px;
}

:deep(.el-dialog) {
  position: absolute;
}

/* 添加自定义header样式 */
.dialog-header-custom {
  width: 100%;
  height: 100%;
  cursor: move;
  user-select: none;
  padding: 20px;
  font-size: 16px;
  font-weight: 500;
}

/* 确保没有覆盖 el-button 的样式 */
.chat-input .el-button {
  /* 移除任何自定义样式 */
}
</style>
